//
//  TodayViewController.swift
//  KebiaoWiget
//
//  Created by David on 2016/12/2.
//  Copyright © 2016年 David. All rights reserved.
//

import UIKit
import NotificationCenter

let GROUP_URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.KebiaoWiget")!

class TodayViewController: UIViewController, NCWidgetProviding, UITableViewDelegate, UITableViewDataSource {
    
    var tableView: UITableView!
    var todayClass: NSArray?
    
    var currentWeek = 1
    var fontColor = UIColor.white
    
    var tomorrow = false
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view from its nib.
        if #available(iOSApplicationExtension 10.0, *){
            self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded
            fontColor = UIColor.black
        }
        
        let setting = NSDictionary(contentsOf: GROUP_URL.appendingPathComponent("setting.plist"))
        if setting != nil{
            let format = DateFormatter()
            format.dateFormat = "yyyy-MM-dd"
            let todayWeek = Calendar.current.component(.weekOfYear, from: Date())
            
            let weekNum = setting!.object(forKey: "firstWeek") as! Int
            
            currentWeek = (53 + todayWeek - weekNum)%53 + 1
//            currentWeek = 13
        }
        
        
        
        tableView = UITableView(frame: view.frame)
        tableView.delegate = self
        tableView.dataSource = self
        view.addSubview(tableView)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        let kebiaoInfos = NSArray(contentsOf: GROUP_URL.appendingPathComponent("/kebiao.plist"))
        
        if kebiaoInfos != nil{
            
            let today = (Calendar.current.component(.weekday, from: Date()) - 2 + 7)%7
//            let today = 4
            
            let outputAry = NSMutableArray()
            
            var lastSession = 0
            
            for row in kebiaoInfos!{
                let rowAry = row as! NSArray
                let classItem = rowAry.object(at: today)
                let classDic = classItem as? NSDictionary
                
                if classDic != nil{
                    let weeks = classDic?.object(forKey: "weeks") as! String
                    let weeksRange = weeks.components(separatedBy: "-")
                    if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                        let eo = classDic?.object(forKey: "eo") as! Int
                        if eo == 0 || (currentWeek%2 == eo%2){
                            outputAry.add(classDic!)
                            let thisClassSessions = classDic?.object(forKey: "sections") as! String
                            let thisSession = Int(thisClassSessions.components(separatedBy: ",")[0])!
                            if thisSession > lastSession {
                                lastSession = thisSession
                            }
                        }
                    }
                }else{
                    let multiClassAry = classItem as? NSArray
                    if multiClassAry != nil {
                        for item in multiClassAry!{
                            let aClassDic = item as? NSDictionary
                            if aClassDic != nil {
                                let weeks = aClassDic?.object(forKey: "weeks") as! String
                                let weeksRange = weeks.components(separatedBy: "-")
                                if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                                    let eo = aClassDic?.object(forKey: "eo") as! Int
                                    if eo == 0 || (currentWeek%2 == eo%2){
                                        outputAry.add(aClassDic!)
                                        let thisClassSessions = aClassDic?.object(forKey: "sections") as! String
                                        let thisSession = Int(thisClassSessions.components(separatedBy: ",")[0])!
                                        if thisSession > lastSession {
                                            lastSession = thisSession
                                        }
                                    }
                                }
                            }
                        }
                    }else{
                        
                    }
                }
            }
            /*
            for item in kebiaoInfos! {
                let classItem = item as? NSDictionary
                if classItem != nil{
                    let weekday = classItem?.object(forKey: "weekday") as! String
                    let column = _get_weekday(name: weekday, starter: 1)!
                    
                    if column == today {
                        
                        let weeks = classItem?.object(forKey: "weeks") as! String
                        let weeksRange = weeks.components(separatedBy: "-")
                        if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                            let eo = classItem?.object(forKey: "eo") as! Int
                            if eo == 0 || (currentWeek%2 == eo%2){
                                outputAry.add(classItem!)
                                print(classItem!)
                                let thisClassSessions = classItem?.object(forKey: "sections") as! String
                                let thisSession = Int(thisClassSessions.components(separatedBy: ",")[0])!
                                if thisSession > lastSession {
                                    lastSession = thisSession
                                }
                            }
                        }
                        
                        
                    }
                }
            }
            */
            let timeFormate = DateFormatter()
            timeFormate.dateFormat = "HH:mm"
            let now = timeFormate.string(from: Date())
            
            if outputAry.count != 0{
                
                if now >= TIME_TABLE[lastSession/2] {
                    tomorrow = true
                    let tomorrowDay = (today + 1) % 7
                    
                    outputAry.removeAllObjects()
                    
                    for row in kebiaoInfos!{
                        let rowAry = row as! NSArray
                        let classItem = rowAry.object(at: tomorrowDay)
                        let classDic = classItem as? NSDictionary
                        
                        if classDic != nil{
                            let weeks = classDic?.object(forKey: "weeks") as! String
                            let weeksRange = weeks.components(separatedBy: "-")
                            if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                                let eo = classDic?.object(forKey: "eo") as! Int
                                if eo == 0 || (currentWeek%2 == eo%2){
                                    outputAry.add(classDic!)
                                    let thisClassSessions = classDic?.object(forKey: "sections") as! String
                                    let thisSession = Int(thisClassSessions.components(separatedBy: ",")[0])!
                                    if thisSession > lastSession {
                                        lastSession = thisSession
                                    }
                                }
                            }
                        }else{
                            let multiClassAry = classItem as? NSArray
                            if multiClassAry != nil {
                                for item in multiClassAry!{
                                    let aClassDic = item as? NSDictionary
                                    if aClassDic != nil {
                                        let weeks = aClassDic?.object(forKey: "weeks") as! String
                                        let weeksRange = weeks.components(separatedBy: "-")
                                        if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                                            let eo = aClassDic?.object(forKey: "eo") as! Int
                                            if eo == 0 || (currentWeek%2 == eo%2){
                                                outputAry.add(aClassDic!)
                                                let thisClassSessions = aClassDic?.object(forKey: "sections") as! String
                                                let thisSession = Int(thisClassSessions.components(separatedBy: ",")[0])!
                                                if thisSession > lastSession {
                                                    lastSession = thisSession
                                                }
                                            }
                                        }
                                    }
                                }
                            }else{
                                
                            }
                        }
                    }
                    
                    /*
                    for item in kebiaoInfos! {
                        let classItem = item as? NSDictionary
                        if classItem != nil{
                            let weekday = classItem?.object(forKey: "weekday") as! String
                            let column = _get_weekday(name: weekday, starter: 1)!
                            
                            if column == tomorrowDay {
                                
                                let weeks = classItem?.object(forKey: "weeks") as! String
                                let weeksRange = weeks.components(separatedBy: "-")
                                if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                                    let eo = classItem?.object(forKey: "eo") as! Int
                                    if eo == 0 || (currentWeek%2 == eo%2){
                                        outputAry.add(classItem!)
                                    }
                                }
                                
                                
                            }
                        }
                    }
                    */
                }
            }else{
                
                if now >= "22:00" {
                    tomorrow = true
                    let tomorrowDay = (today + 1) % 7
                    
                    outputAry.removeAllObjects()
                    
                    for row in kebiaoInfos!{
                        let rowAry = row as! NSArray
                        let classItem = rowAry.object(at: tomorrowDay)
                        let classDic = classItem as? NSDictionary
                        
                        if classDic != nil{
                            let weeks = classDic?.object(forKey: "weeks") as! String
                            let weeksRange = weeks.components(separatedBy: "-")
                            if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                                let eo = classDic?.object(forKey: "eo") as! Int
                                if eo == 0 || (currentWeek%2 == eo%2){
                                    outputAry.add(classDic!)
                                    let thisClassSessions = classDic?.object(forKey: "sections") as! String
                                    let thisSession = Int(thisClassSessions.components(separatedBy: ",")[0])!
                                    if thisSession > lastSession {
                                        lastSession = thisSession
                                    }
                                }
                            }
                        }else{
                            let multiClassAry = classItem as? NSArray
                            if multiClassAry != nil {
                                for item in multiClassAry!{
                                    let aClassDic = item as? NSDictionary
                                    if aClassDic != nil {
                                        let weeks = aClassDic?.object(forKey: "weeks") as! String
                                        let weeksRange = weeks.components(separatedBy: "-")
                                        if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                                            let eo = aClassDic?.object(forKey: "eo") as! Int
                                            if eo == 0 || (currentWeek%2 == eo%2){
                                                outputAry.add(aClassDic!)
                                                let thisClassSessions = aClassDic?.object(forKey: "sections") as! String
                                                let thisSession = Int(thisClassSessions.components(separatedBy: ",")[0])!
                                                if thisSession > lastSession {
                                                    lastSession = thisSession
                                                }
                                            }
                                        }
                                    }
                                }
                            }else{
                                
                            }
                        }
                    }
                    
                    /*
                    for item in kebiaoInfos! {
                        let classItem = item as? NSDictionary
                        if classItem != nil{
                            let weekday = classItem?.object(forKey: "weekday") as! String
                            let column = _get_weekday(name: weekday, starter: 1)!
                            
                            if column == tomorrowDay {
                                
                                let weeks = classItem?.object(forKey: "weeks") as! String
                                let weeksRange = weeks.components(separatedBy: "-")
                                if currentWeek >= Int(weeksRange[0])! && currentWeek <= Int(weeksRange[1])! {
                                    let eo = classItem?.object(forKey: "eo") as! Int
                                    if eo == 0 || (currentWeek%2 == eo%2){
                                        outputAry.add(classItem!)
                                    }
                                }
                                
                                
                            }
                        }
                    }
                    */
                }
                
            }
            
            
            
            todayClass = NSArray(array: outputAry)
//            print(todayClass)
            preferredContentSize = CGSize(width: 0, height: CGFloat(todayClass!.count+1)*64 + 32)
            tableView.reloadData()
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if todayClass != nil{
            if todayClass!.count > 0{
                return todayClass!.count + 1
            }
        }
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.row == 0{
            return 32
        }
        return 64
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        cell.selectionStyle = .none
        if indexPath.row == 0{
            let label = UILabel(frame: CGRect(x: 0, y: 8, width: view.bounds.width, height: 16))
            label.font = UIFont.systemFont(ofSize: 14)
            label.textAlignment = .center
            label.textColor = fontColor
            
            let today = Calendar.current.component(.weekday, from: Date())
            
            var showDay = _get_weekday(num: today - 1, starter: 0)
            
            if tomorrow {
                showDay = "明天 \(_get_weekday(num: today%7, starter: 0)!)"
                label.font = UIFont.boldSystemFont(ofSize: 14)
            }
            
            
            label.text = "第\(currentWeek)周 \(showDay!)"
            
            
            
            cell.addSubview(label)
        }else{
            if todayClass != nil{
                if todayClass!.count > 0{
                    
                    let thisClass = todayClass?.object(at: indexPath.row-1) as! NSDictionary
                    
                    let placeLabel = UILabel(frame: CGRect(x: 16, y: 8, width: 72, height: 48))
                    placeLabel.numberOfLines = 2
                    placeLabel.font = UIFont.systemFont(ofSize: 20)
                    placeLabel.textColor = fontColor
                    cell.addSubview(placeLabel)
                    let place = thisClass.object(forKey: "place") as? String
                    if place != nil{
                        let match = shortThePlace(place: place!)
                        
                        if match != nil{
                            var out = ""
                            for i in 0..<match!.count{
                                out += "\"\(match![i])\""
                                if i != match!.count - 1{
                                    out += ","
                                }
                            }
                            placeLabel.text = out
                        }else{
                            placeLabel.text = place
                        }
                    }
                    
                    
                    let nameLabel = UILabel(frame: CGRect(x: 96, y: 8, width: view.bounds.width - 96, height: 48))
                    nameLabel.text = thisClass.object(forKey: "class_name") as? String
                    nameLabel.textColor = fontColor
                    cell.addSubview(nameLabel)
                }else{
                    let label = UILabel(frame: CGRect(x: 16, y: 8, width: view.bounds.width, height: 48))
                    label.textColor = fontColor
                    cell.addSubview(label)
                    
                    var noClass = "今天"
                    if tomorrow {
                        noClass = "明天"
                    }
                    noClass += "没课，嘻嘻^_^"
                    label.text = noClass
                }
            }
        }
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row > 0{
            extensionContext?.open(URL(string: "mykebiao://\(indexPath.row)")!, completionHandler: nil)
        }
    }
    
    func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
        // Perform any setup necessary in order to update the view.
        
        // If an error is encountered, use NCUpdateResult.Failed
        // If there's no update required, use NCUpdateResult.NoData
        // If there's an update, use NCUpdateResult.NewData
        
        completionHandler(NCUpdateResult.newData)
    }
    
    @available(iOSApplicationExtension 10.0, *)
    func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
        if activeDisplayMode == .compact {
            preferredContentSize = maxSize
        }else{
            if todayClass != nil{
                preferredContentSize = CGSize(width: maxSize.width, height: CGFloat(todayClass!.count)*64 + 32)
            }
            
        }
    }
    
}

func shortThePlace(place: String) -> [String]? {
    do{
        let regex = try NSRegularExpression(pattern: "[a-zA-Z0-9].*", options: .caseInsensitive)
        let res = regex.matches(in: place, options: .withoutAnchoringBounds, range: NSMakeRange(0, place.characters.count))
        var output:[String] = []
        for check in res{
            output.append(NSString(string: place).substring(with: check.range) as String)
        }
        if output.count == 0{
            return nil
        }
        return output
    }catch {
        print(error)
    }
    return nil
}
